package com.bgdCA.service.impl;

import com.bgdCA.domain.SendInfo;
import com.bgdCA.response.CodeMsg;
import com.bgdCA.response.Result;
import com.bgdCA.service.IMailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.internet.MimeMessage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;


/**
 * @ClassName MailServiceImpl
 * @Description TODO
 * @Author AlvinZheng
 * @Date 2020/7/27 10:42
 * @Version 1.0
 **/
@Component
@Slf4j
public class MailServiceImpl implements IMailService {

//    @Autowired
//    private JavaMailSenderImpl jms;

    @Autowired
    TemplateEngine templateEngine;

    @Value("${spring.mail.username}")
    private String fromName;

    public JavaMailSenderImpl generateJms(String fromName,String host,String password){
        JavaMailSenderImpl jms = new JavaMailSenderImpl();
        jms.setHost(host);
        jms.setUsername(fromName);
        jms.setPassword(password);
        jms.setDefaultEncoding("Utf-8");
        Properties p = new Properties();
        p.setProperty("mail.smtp.auth", "true");
        jms.setJavaMailProperties(p);
        return jms;
    }
    public JavaMailSenderImpl generateJmsDefault(){
        JavaMailSenderImpl jms = new JavaMailSenderImpl();
        jms.setHost("smtp.qq.com");
        jms.setUsername("223337742@qq.com");
        jms.setPassword("zemcxejlljhibhjh");
        jms.setDefaultEncoding("Utf-8");
        Properties p = new Properties();
        p.setProperty("mail.smtp.auth", "true");
        jms.setJavaMailProperties(p);
        return jms;
    }
    public boolean isWholeEmailProperties(SendInfo sendInfo){
        String fromAddress = sendInfo.getFromAddress();
        String host = sendInfo.getHost();
        String password = sendInfo.getPassword();
        if (fromAddress==null||host==null||password==null){
            return false;
        }
        return true;
    }
    @Override
    public Result sendHtmlMail(SendInfo sendInfo) {
        HashMap errorEmailList = new HashMap();
        JavaMailSenderImpl jms;
        /*判断是否为自定义发件人*/
        if (isWholeEmailProperties(sendInfo)){
            jms = generateJms(sendInfo.getFromAddress(),sendInfo.getHost(),sendInfo.getPassword());
        }else {
            jms = generateJmsDefault();
        }
        System.out.println("jmspwd"+jms.getPassword());
        System.out.println("jmspHost"+jms.getHost());
        System.out.println("jmsUserName"+jms.getUsername());
        MimeMessage message = jms.createMimeMessage();
        for (int i = 0; i < sendInfo.getTo().length; i++) {
            try {
                MimeMessageHelper helper = new MimeMessageHelper(message, true);
                /*不管是完整的还是不完整的传值，都默认从实体类获得邮件地址*/
                helper.setFrom(sendInfo.getFromAddress());
                String to = sendInfo.getTo()[i];
                /*在头部追加内容*/
                //    System.out.println(to.toString());
                String content = sendInfo.getContent();
                /*在头部追加内容 End*/
                if (sendInfo.isUseGreeting()) {
                    String toName = sendInfo.getToName()[i];
                    content = "<div>您好," + toName + "!</div>" + sendInfo.getContent();
                }
                helper.setTo(to);
                helper.setSubject(sendInfo.getSubject());
                helper.setText(content, sendInfo.isHtml());
                if (sendInfo.isUseAttachment()) {
                    for (MultipartFile file : sendInfo.getAttachment()) {
                        helper.addAttachment(file.getOriginalFilename(), file);
                    }
                }
                jms.send(message);


            } catch (Exception e) {
                errorEmailList.put(sendInfo.getToName()[i],sendInfo.getTo()[i]);
            }
        }
        log.info("邮件已经发送");
        return Result.success(errorEmailList);
    }

    @Override
    public void sendTemplateMail(String[] to, String subject, String activeHref) {
        Context context = new Context();
        context.setVariable("activeHref", activeHref);
        String emailContent = templateEngine.process("registerTemplate", context);
        sendHtmlMail(new SendInfo(to, subject, emailContent, null, true, false,true));
    }

    @Override
    public void registerTemplateMail(String[] to, String subject, String activeHref) {
        Context context = new Context();
        context.setVariable("activeHref", activeHref);
        String emailContent = templateEngine.process("registerTemplate", context);
        SendInfo sendInfo = new SendInfo(to, subject, emailContent, null, true, false,true);
        sendInfo.setUseGreeting(false);
        sendHtmlMail(sendInfo);
    }


    @Override
    public void resetTemplateMail(String[] to, String subject, String captcha) {
        Context context = new Context();
        context.setVariable("captcha", captcha);
        String emailContent = templateEngine.process("resetPsdTemplate", context);
        SendInfo sendInfo = new SendInfo(to, subject, emailContent, null, true, false,true);
        sendInfo.setUseGreeting(false);
        sendHtmlMail(sendInfo);

    }
}
